<%@ include file="/WEB-INF/views/commonJSTL.jsp" %>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>							
<head>
<title>${s_UserPharmacy.pharmacy.name}</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<%@ include file="/WEB-INF/views/commonResources.jsp" %>

<c:set var="tempSelected" scope="page"><fmt:message key="form.selected"/></c:set>	

<script type="text/javascript">
	var listPharmacyStock = [];
	<c:forEach var="pharmacyStock" items="${listPharmacyStock}">
		var pharmacyStock = {pharmacyId:"<c:out value="${pharmacyStock.pharmacystockPK.pharmacyId}"/>",
				stockId:"<c:out value="${pharmacyStock.pharmacystockPK.stockId}"/>",
				phone:"<c:out value="${pharmacyStock.stock.phone}"/>",
				userId:"<c:out value="${pharmacyStock.stock.userpharmacy.user.userId}"/>",
				address:"<c:out value="${pharmacyStock.stock.address}"/>",
				remark:"<c:out value="${pharmacyStock.stock.remark}"/>",
				name:"<c:out value="${pharmacyStock.stock.name}"/>"};
		listPharmacyStock.push(pharmacyStock);
	</c:forEach>  

	var listUserPharmacy = [];
	<c:forEach var="userPharmacy" items="${listUserPharmacy}">
		var userPharmacy = {pharmacyId:"<c:out value="${userPharmacy.userpharmacyPK.pharmacyId}"/>",
				userId:"<c:out value="${userPharmacy.userpharmacyPK.userId}"/>",
				name:"<c:out value="${userPharmacy.user.name}"/>"};
		listUserPharmacy.push(userPharmacy);
	</c:forEach> 
	
	$(document).ready(function(){
		$("#dialogo").dialog({
			autoOpen: false,
	        title: "Almacén",
			height: 350,
			width: 550,
			modal: true,
			buttons: {
	            "Aceptar": function() {
	            	var flag = $("#formDialog").valid();
	                if(flag){
	                	ajaxDataStockAddEdit();
	                } 
	            },
	            Cancelar: function() {
	            	location.href = "dataStock?_menuId=2&_subMenuId=1&_optionId=1"; 
	                $( this ).dialog( "close" );
	            }
			},
			close: function() {
				mainDataStock();          // implementar lo que convenga
			}
		});	
		
		//permit only numbers
		$('.numberOnlyNumber').keyup(function () {
	         if (this.value != this.value.replace(/[^0-9]/g,'')) {
	            this.value = this.value.replace(/[^0-9]/g, '');
	         }
	     });
		
		//permit only text
		$('.lettersOnly').keyup(function () {
	         if (this.value != this.value.replace(/[^A-Za-z\s]/g, '')) {
	            this.value = this.value.replace(/[^A-Za-z\s]/g, '');
	         }
	     });
		
		$( "#dialog-message" ).dialog({
			modal: true,
			buttons: {
				Ok: function() {
					$( this ).dialog( "close" );
				}
			},
			close: function() {
				mainDataStock();         // implementar lo que convenga
			}
		});	 
		
		
		$("#_stockId").change(function(){
			if($("#_stockId").val() != ''){
		        $("#_stockId option:selected").each(function (){
		        	ajaxDataStockSelectedPharmacyStock();
		        });
	        }else{
	        	$('#formDialog').each(function(){
	                this.reset();
	            });
				/* var element = $("#_userId");
				var id = element.attr('id');
				alert(element)
				 $('#'+id+'> option[value=""]').attr('selected', 'selected'); */
	        }
	    });
		
		
		
		$( "#dialogoTipoAlert" ).dialog({
      	  	autoOpen: false, // no abrir automáticamente
      	  	title: "Advertencia",
      	  	resizable: true, //permite cambiar el tamaño
            height:150, // altura
            modal: true, //capa principal, fondo opaco
            buttons: { //crear botón de cerrar
            	 "Aceptar": function() {
            		 	$( this ).dialog( "close" );
            		 
            	}
            }
          });
        		          
          $.fn.AlertDialog = function(res){	
        	  $('#dialogoText').text(res);
              $("#dialogoTipoAlert").dialog("open");
          }
		
	});
	function ajaxDataStockAddEdit(){
		$.ajax({
            type: 'POST',
            url: 'ajaxDataStockAddEdit',
            data: $('#formDialog').serialize(),
            success: function(res){
            	switch(res){
            	case '':
            		$.fn.AlertDialog('No se hizo Nada');
            	  break;
            	case '-2':
            		$.fn.AlertDialog('Los datos actuales ya existen');
            	  break;
            	default:
            		mainDataStock();
            	}
        },
    	error:function(){alert("Error! into ajax")}
        });
        $( this ).dialog("close");
	}	
	function ajaxDataStockSelectedPharmacyStock(){
		var pharmacyId	= parseInt("<c:out value="${s_UserPharmacy.pharmacy.pharmacyId}"/>",10);
		var stockId 	= $("#_stockId").val();		
		for(var i=0; i<listPharmacyStock.length; i++){
			var pharmacyStock = listPharmacyStock[i];
	    	if(pharmacyStock.stockId == stockId && pharmacyStock.pharmacyId == pharmacyId){
	    		$("#_userId").val(pharmacyStock.userId);	
	    		$("#name").val(pharmacyStock.name);
           		$("#address").val(pharmacyStock.address);
           		$("#phone").val(pharmacyStock.phone);	
           		$("#remark").val(pharmacyStock.remark);	
	    	}
		} 
		/*
		if(stockId != null){
			$.ajax({
		        type: 'GET',
		        dataType: "json",
		        url: 'ajaxDataStockSelectedPharmacyStock',
		        data:{stockId:stockId,pharmacyId:pharmacyId},
		        success: function(data){ 	           	
		           	if(data[0] != ''){
		        		var obj = data[0];
		           		$("#_userId").val(obj.userId);		           	
		           		$("#name").val(obj.name);
		           		$("#address").val(obj.address);
		           		$("#phone").val(obj.phone);		           	
		           	}
		        },
		    	error:function(){alert("Error! into ajax")}
		    });
		}	*/
	}	
	
	function showFormDataStockEdit(stockId,pharmacyId){	
    	$('#formDialog').each(function(){
            this.reset();
        });        
    	$("#_stockId").empty().append("<option value=''><c:out value="${tempSelected}"/></option>");
		for(var i=0; i<listPharmacyStock.length; i++){
			var pharmacyStock = listPharmacyStock[i];
			$("#_stockId").append("<option value='"+pharmacyStock.stockId+"'>"+pharmacyStock.name+"</option>");
	    	if(pharmacyStock.stockId == stockId && pharmacyStock.pharmacyId == pharmacyId){
	    		//$("#_stockId").empty().append("<option value='"+pharmacyStock.stockId+"'>"+pharmacyStock.name+"</option>");
	    		$("#_stockId").prop('disabled', true);
	    		$("#_userId").val(pharmacyStock.userId);	
	    		$("#_stockId").val(pharmacyStock.stockId);	
	    		$("#_stockIdTemp").val(pharmacyStock.stockId);	
	    		$("#name").val(pharmacyStock.name);
           		$("#address").val(pharmacyStock.address);
           		$("#phone").val(pharmacyStock.phone);	
           		$("#remark").val(pharmacyStock.remark);          		
	    	}
		}    	
    	$("#action").val(1);
    	$("#titleForm").text("Editar Almacén");
        $("#dialog:ui-dialog").dialog("destroy");
        $("#dialogo").dialog("open");
	}
	
	function showFormDataStockAdd(){		
		$("#_stockId").prop("readonly",false);
		$('#formDialog').each(function(){
            this.reset();
        });        
        $("#titleForm").text("Nuevo Almacén");
        $("#dialog:ui-dialog").dialog("destroy");
        $("#dialogo").dialog("open");
	}		
	function mainDataStock(){
		location.href = "dataStock?_menuId=2&_subMenuId=1&_optionId=1";
	}
	function removeDataStock(stockId,name){
		if(confirm("¿Esta seguro de eliminar el almacen ''"+name+"''?")){
	       	   $.ajax({
	           	  url: "ajaxDataStockRemove",
	              type: "GET",
	              data:{stockId:stockId, name:name},
	              success:function(res){
	                 location.href = "dataStock?_menuId=2&_subMenuId=1&_optionId=1";
	              },
	                 error: function(res){ alert("Error! al eliminar el almacen esta siendo utilizado por otra persona o programa."); }
	          });
	      }
	}
	
</script>
</head>

<body>
<div id="top-wrap">
	<%@include file="../../../head.jsp"  %>
	<div id="bodySpace">
		
	    <div class="clearfix" id="middle" style="position: absolute">  <!-- aqui va la ruta -->
	        <!-- aqui va el arbol de entrada -->
	        <div id="breadcrumb">
	            <ul>
                	<li><a href="<spring:url value="/mainFront?" htmlEscape="true" />">Home</a></li>	
                    <li><span style="color:#666"><fmt:message key="title.admin"/></span></li>
                    <li><span style="color:#666"><fmt:message key="title.adminStock"/></span></li>
                    <li class="current-page"><span class="end"><span class="middle"><fmt:message key="title.dataStock"/></span></span></li>
                </ul>
	        </div>
	    </div>
	    
	    <div id="principal">
            <!-- izquierda -->
            <div class="cuerpo2y" style="border: 0px solid"><br/><br/><!-- estos break son necesarios ya q uso absolute en css  cuerpo izquierdo-->
                <div class="izq">
					<%@include file="../../../bodyIzq.jsp" %>	
                </div>
                
                <div class="medio" style="border: 0px solid">
					<h2 class="decorado"><fmt:message key="title.dataStock"/></h2>&nbsp;&nbsp;
					<h3 class="decorado"><fmt:message key="title.list.stock"/></h3></br>
					
					<div id="imgLoad" style="float: left;width: 100%;display: none;"><img src="<c:url value="/resources/images/imgLoad/ajax-loader.gif" />" width="32" height="32" alt="ajax-loader.gif" style="position:absolute; top:30%; left:50%;"/></div> 
					<div id="dataStock">
						<div id="dialogoTipoAlert">
							<div id="dialogoText"></div>
						</div>					
					
						<div id="dialogo"><br/>
							<h2 class="decorado" id="titleForm"></h2><br/>
							<form id="formDialog">
								<input type="hidden" name="action" id="action" value="0" />
								<input type="hidden" name="_stockIdTemp" id="_stockIdTemp" value="0" />
								
								<c:set var="stockShow" scope="page"><fmt:message key="show.form.selected.stock"/>.</c:set>		
								<div style="clear:both;">
									<label class="form_align30"><fmt:message key="form.stock"/> :</label>
									<select name="_stockId" id="_stockId" class="required form_input_align" title="${stockShow}">
										<option value=""><fmt:message key="form.selected"/></option>
										<c:forEach var="item" items="${listPharmacyStock}">
											<option value="${item.stock.stockId}">${item.stock.name}</option>
										</c:forEach>
										<option value="0">Otro</option>
									</select>
									<label class="error">*</label>
								</div>
								
								<c:set var="responsibleShow" scope="page"><fmt:message key="show.form.selected.responsible"/>.</c:set>		
								<div style="clear:both;">
									<label class="form_align30"><fmt:message key="form.responsible"/> :</label>
									<select name="_userId" id="_userId" class="form_input_align" title="${responsibleShow}">
										<option value=""><fmt:message key="form.selected"/></option>
										<c:forEach var="item" items="${listUserPharmacy}">
											<option value="${item.userpharmacyPK.userId}">${item.user.name}</option>
										</c:forEach>
									</select>
									<label class="error">*</label>
								</div>
								
								<c:set var="showName" scope="page"><fmt:message key="show.form.name"/>.</c:set>		
								<div style="clear:both;">
									<label class="form_align30"><fmt:message key="form.name"/> :</label>
	                                <input type="text" name="name" id="name" value="" class="required form_input_align" title="${showName}" placeholder="texto"/>
									<label class="error">*</label>
								</div>
								
								<c:set var="showAddress" scope="page"><fmt:message key="show.form.address"/>.</c:set>		
								<div style="clear:both;">
									<label class="form_align30"><fmt:message key="form.address"/> :</label>
	                                <input type="text" name="address" id="address" value="" class="form_input_align" title="${showAddress}" placeholder="texto"/>
								</div>
								
								<c:set var="showPhone" scope="page"><fmt:message key="show.form.phone"/>.</c:set>		
								<div style="clear:both;">
									<label class="form_align30"><fmt:message key="form.phone"/> :</label>
	                                <input type="text" name="phone" id="phone" value="" class="form_input_align numberOnlyNumber" title="${showPhone}" placeholder="números"/>
								</div>

								<c:set var="showRemark" scope="page"><fmt:message key="show.form.remark"/>.</c:set>	
								<div style="clear:both;">
									<label class="form_align30"><fmt:message key="form.remark"/> :</label>
									<textarea name="remark" id="remark" class="form_input_align" title="${showRemark}" placeholder="texto"></textarea>
								</div>
							</form>
						</div>
					
						<table class="miReporte" style="width: 100%">
							<tr>
								<td style="text-align: right"><input type="button" class="boton" value="<fmt:message key="button.add"/> <fmt:message key="title.stock"/>" onclick="showFormDataStockAdd()" title='<fmt:message key="onclick.add"/> <fmt:message key="title.stock"/>.'/></td>
							</tr>
						</table>
						<table class="tabla_decorado" style="width: 100%">
							<thead>
								<tr>
									<th width="4%" class="th_decoradoRowspan"><fmt:message key="table.num"/></th>
									<th width="16%" class="th_decoradoRowspan"><fmt:message key="table.name"/></th>
									<th width="10%" class="th_decoradoRowspan"><fmt:message key="table.typeStock"/></th> 
									<th width="10%" class="th_decoradoRowspan"><fmt:message key="table.responsible"/></th>
									<th width="15%" class="th_decoradoRowspan"><fmt:message key="table.address"/></th>
									<th width="10%" class="th_decoradoRowspan"><fmt:message key="table.phone"/></th>
									<th width="15%" class="th_decoradoRowspan"><fmt:message key="table.remark"/></th>
									<th width="20%" class="th_decoradoRowspan"><fmt:message key="table.actions"/></th>
								</tr>
							</thead>
							<tbody>
								<c:set var="i" value="1"/>
								<c:forEach var="item" items="${listPharmacyStock}"> 
									<tr class="tr_decorado">
										<td class="th_decorado" style="text-align: center">${i}</td>
										<td class="th_decorado">${item.stock.name}</td>
										<c:if test="${item.main == true}">
										<td class="th_decorado">Alamacen Principal</td>
										</c:if>
										<c:if test="${item.main == false}">
										<td class="th_decorado">Alamacen Secundario</td>											
										</c:if>
										<td class="th_decorado">${item.stock.userpharmacy.user.name}</td>
										<td class="th_decorado">${item.stock.address}</td>	
										<td class="th_decorado">${item.stock.phone}</td>
										<td class="th_decorado">${item.stock.remark}</td>
										<td class="td_decoradoDerecha" style="text-align: center">
											<input type="button" value="<fmt:message key="button.edit"/>" onclick="showFormDataStockEdit('${item.pharmacystockPK.stockId}','${item.pharmacystockPK.pharmacyId}')" class="botonRep" title="<fmt:message key="onclick.edit"/> ${item.stock.name}"/>
											<input type="button" value="<fmt:message key="button.remove"/>" onClick="removeDataStock('${item.pharmacystockPK.stockId}','${item.stock.name}')" class="botonRep" title="<fmt:message key="onclick.remove"/> ${item.stock.name}"/>
										</td>
									</tr>
									<c:set var="j" value="1"/>
									<c:set var="i" value="${i+j}"/>
								</c:forEach>
							</tbody>
						</table>
					</div>	                               
                </div>
            </div><!--end of leftPan-->
            
            <div class="yDer" style="border: 1px solid #ccc;">
                  <%@include file="../../../notices.jsp" %>                       
            </div><!--end of rightPan-->
        </div><!--end main content -->
	</div>
</div>
</body>
</html>
